import graphqlClient from '../../api/GraphqlConfig';
import {GET_FILE_UPLOAD_URL, GET_FILE_DOWNLOAD_URL} from "../gql/FileGQL.tsx";


class FileService {

    private async getUploadFile(fileKey: string): Promise<FileUrl> {
        const strings = fileKey.split(":");
        if (strings.length != 2) {
            throw new Error("Invalid file key");
        }
        // 修正参数名和变量引用
        const response = await graphqlClient.query<{ file: {getFileUploadUrl: FileUrl} }>({
            query: GET_FILE_UPLOAD_URL,
            variables: {
                bucketName: strings[0],
                objectName: strings[1],
                expiresInSeconds: 3600
            }
        });
        // GraphQL查询不需要json()解析
        return response!.data!.file.getFileUploadUrl;
    }

    async getDownloadUrl(fileKey: string): Promise<FileUrl> {
        const strings = fileKey.split(":");
        if (strings.length != 2) {
            throw new Error("Invalid file key");
        }
        // 使用专门的下载URL查询
        const response = await graphqlClient.query<{ file: { getFileDownloadUrl: FileUrl } }>({
            query: GET_FILE_DOWNLOAD_URL,
            variables: {
                bucketName: strings[0],
                objectName: strings[1],
                expiresInSeconds: 3600
            }
        });
        return response!.data!.file.getFileDownloadUrl;
    }

    // 生成随机文件名
    private generateRandomFileName(file: File): string  {
        const extension = file.name.split('.').pop();
        const randomName = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
        return `${randomName}.${extension}`;
    };

    // 上传文件到服务器
     async uploadFile(file: File, bucketName: string): Promise<string> {
        try {
            // 生成随机文件名
            const fileName = this.generateRandomFileName(file);
            const fileKey = `${bucketName}:${fileName}`;

            // 获取上传URL
            const uploadInfo = await this.getUploadFile(fileKey);

            if (!uploadInfo.url) {
                throw new Error('Failed to get upload URL');
            }

            // 使用fetch上传文件
            const response = await fetch(uploadInfo.url, {
                method: 'PUT',
                headers: {
                    'Content-Type': file.type,
                    'Content-Length': file.size.toString()
                },
                body: file
            });

            if (!response.ok) {
                throw new Error(`Upload failed with status ${response.status}`);
            }

            // 返回文件key用于存储
            return fileKey;
        } catch (error) {
            console.error('File upload error:', error);
            throw error;
        }
    }
}

export interface FileUrl {
    url?: string;
    expiresInSeconds?: number;
}


export const fileService = new FileService();
